/**
  * @Author: songgh
  * @Date: 2021-09-20 14:41:08
  * @LastEditors: songgh
  * @LastEditTime: 2021-09-20 15:41:08
  * @Description: axios interceptor
  */
import axios from 'axios';
import { Notify } from 'vant';

export default class HttpRequest {
    private instance;
    public get: Function = axios.get;
    public post: Function = axios.post;
    public put: Function = axios.put;
    public delete: Function = axios.delete;

    constructor(baseURL = '', timeout = 60000 * 3) {
        this.instance = axios.create({
            baseURL,
            timeout,
            withCredentials: true
        });
        this.interceptors();
        return this.instance;
    }

    private interceptors(instance = this.instance) {
        instance.interceptors.request.use(config => {
            return config;
        }, error => {
            return Promise.reject(error);
        });

        instance.interceptors.response.use(
            response => {
              const { status, config } = response;
              let { showErrorMessage } = config;
              if (showErrorMessage === undefined) {
                showErrorMessage = true;
              }
              if (status === 200) {
                const { data } = response;
                const { code, message, error } = data;
                if (code !== 1000) {
                  if (message !== "未登录或登录失效，请重新登录") {
                    showErrorMessage && Notify({ type: 'danger', message });
                  }
                  // this.errorHook(response);
                  return Promise.reject(message);
                }
                if (error) {
                  showErrorMessage && Notify({ type: 'danger', message: `${error.code} ${error.message}` })
                  // this.errorHook(response);
                  return Promise.reject(error.message);
                }
                return Promise.resolve(data);
              } else {
                // this.errorHook(response);
                return showErrorMessage && Notify({ type: 'danger', message: `${status}` })
              }
            },
            error => {
              // this.errorHook(error.response);
              Notify({ type: 'danger', message: `${error.message}` })
              return Promise.reject(error.response);
            }
          );
    }
}